# -*- coding:utf-8 -*-
import hive_bind as myHive

def query(host,port,database,username,query,password):
	try:
		cursor=myHive.connect(host=host,port=port,username=username,database=database,password=password).cursor()
		cursor.execute(query)
	except Exception as e:
		#cursor.close()
		raise e
	return cursor

def table_exist(host,port,database,table_name,username,password):
	cursor=query(host,port,database,username,"show tables",password=password)
	all_tables=cursor.fetchall()
	for row in all_tables:
		print row[0]
		if row[0]==table_name.strip() :
			return True
	cursor.close()
	return False

def partition_exist(host,port,database,table_name,partition,username,password):
	cursor=query(host,port,database,username,"show partitions "+table_name,password=password)
	all_partitions=cursor.fetchall()
	for row in all_partitions:
		print row[0]
		if row[0]==partition.strip():
			return True
	cursor.close()
	return False

def drop_partition(host,port,database,table_name,partition,username,password):
	sql="ALTER TABLE "+table_name+" DROP IF EXISTS PARTITION ( dt='"+partition+"')"
	print sql
	cursor=query(host,port,database,username,sql,password=password)
	cursor.close()

def drop_table(host,port,database,table_name,username):
	sql="drop table "+table_name
	print sql
	cursor=query(host,port,database,username,sql)
	cursor.close()


def load_raw_data(host,port,database,table_name,location,partition,username,password):
	sql="load data inpath '"+location+"' OVERWRITE into table "+table_name+" partition ( dt='"+partition+"')"
	print sql
	cursor=query(host,port,database,username,sql,password=password)
	cursor.close()